package com.example.springbootdemo.controller;

import com.example.springbootdemo.config.MinioConfig;
import com.example.springbootdemo.util.MinioUtil;
import com.example.springbootdemo.util.Result;
import com.example.springbootdemo.vo.FileVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  minio控制器
 * </p>
 *
 * @author yurenwei
 * @since 2023/9/22
 */
@Slf4j
@Api(tags = "minio接口")
@RestController
@RequestMapping("/api/minio")
public class MinioController {

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig minioConfig;

    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public Result<List<FileVO>> upload(@RequestParam("file") MultipartFile file) {
        List<FileVO> fileList = minioUtil.uploadFile(new MultipartFile[]{file}, minioConfig.getBucket());
        return Result.ok(fileList);
    }

    /**
     * 删除
     *
     * @param fileName 文件名
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestParam("fileName") String fileName) {
        minioUtil.removeFile(minioConfig.getBucket(), fileName);
        return Result.ok();
    }


    /**
     * 文件下载
     *
     * @param fileName 文件名
     * @param response 响应
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream stream = minioUtil.download(minioConfig.getBucket(), fileName);
            ServletOutputStream output = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(stream, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
